// import { Process, Exception, time } from "./__types/yao";

function beforeSave(payload) {
  var user_id = Process("session.Get", "user_id");
  // 如果是admin用户，则不设置user_id
  if (user_id == 1) {
    return [payload];
  }

  payload["user_id"] = user_id;
  console.log("beforeSave-payload-->", payload);
  return [payload];
}

function save(payload) {
  console.log("save-payload-->", payload);
  // 创建优惠券 - 只有admin用户可以创建
  var user_id = Process("session.Get", "user_id");
  if (user_id == 1) {
    var res = Process("models.coupon.save", payload);

    return { code: 200, data: { coupon_id: res }, message: "success" };
  }


  let coupon = Process("models.coupon.Find", payload.id, {});
  if (coupon.user_id != payload.user_id) {
    throw new Exception("该优惠券不属于你", 400);
  }
  if (payload.status == "used" && coupon.status == 'used') {
    throw new Exception("该优惠券已使用", 400);
  }

  // 使用优惠券
  if (payload.status == "used" && coupon.status == 'unused') {
    var res = Process("models.coupon.save", payload);
    return { code: 200, data: { coupon_id: res }, message: "success" };
  }

  // 领取优惠券，需要扣除积分
  let ret = Process("scripts.integral.GetPersonalIntegral");
  if (coupon.points <= 0 || ret.total < coupon.points) {
    throw new Exception("积分不足", 400);
  }
  //  javascript 获取当前系统时间， 格式为 2025-01-07 08:01:05
  var earn_time = new Date().Format("yyyy-MM-dd HH:mm:ss");
  let integral_payload = {
    user_id: payload.user_id,
    points: -coupon.points,
    source: "coupon",
    earn_time: earn_time,
    status: "normal",
    desc: "使用优惠券:" + coupon.code,
  }
  console.log("integral_payload-->", integral_payload);
  var integral_res = Process("models.integral.save", integral_payload);
  var res = Process("models.coupon.save", payload);

  return { code: 200, data: { coupon_id: res, integral_id: integral_res }, message: "success" };
}


function BeforeSearch(query, page, pagesize) {

  let userid = Process("session.Get", "user_id");
  if (userid == 1) {
    return [query, page, pagesize];
  }
  query.wheres.push({ column: "user_id", method: "where", value: userid, op: "eq" }, { column: "user_id", method: "orwhere", op: "null" });
  console.log("coupon before search query----2->", query, page, pagesize);
  return [query, page, pagesize];
}


function GetPersonalIntegral() {
  let user_id = Process("session.Get", "user_id");
  if (!user_id) { throw new Exception("请提供查询用户", 400); }
  // user_id = 3;
  var query = new Query();
  var data = query.Get({
    select: ["user_id", ":SUM(points) as total"],
    from: "integral",
    wheres: [{ ':deleted_at': '删除', '=': null }, { ':user_id': '用户', '=': user_id }],
    groups: [{ field: "user_id", comment: "按用户统计" }],
  });
  if (data.length > 0) {
    return data[0];
  } else {
    return { "total": 0, "user_id": user_id, };
  }
}

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "H+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

